// SmartInput 内容脚本 - 处理网页文字输入

// 动态加载 socket.io 客户端库
function loadSocketIO() {
  return new Promise((resolve, reject) => {
    // 如果已经加载了，直接返回
    if (window.io && typeof window.io === 'function') {
      console.log('Socket.IO 已加载');
      resolve(window.io);
      return;
    }
    
    console.log('开始加载 Socket.IO...');
    
    // 创建 script 标签
    const script = document.createElement('script');
    script.src = chrome.runtime.getURL('socket.io.js');
    script.type = 'text/javascript';
    
    // 设置加载成功回调
    script.onload = () => {
      console.log('Socket.IO 脚本加载完成');
      
      // 检查 io 是否可用
      const checkIO = () => {
        if (window.io && typeof window.io === 'function') {
          console.log('Socket.IO 初始化成功');
          resolve(window.io);
        } else {
          console.log('等待 Socket.IO 初始化...');
          setTimeout(checkIO, 50);
        }
      };
      
      // 立即检查一次
      checkIO();
    };
    
    // 设置加载失败回调
    script.onerror = (error) => {
      console.error('Socket.IO 脚本加载失败:', error);
      reject(new Error('Socket.IO 库加载失败'));
    };
    
    // 添加到页面
    document.head.appendChild(script);
  });
}

let currentInputElement = null;
let smartInputOverlay = null;
let isAutoInsertEnabled = true;
let lastInsertedText = '';
let socket = null;

// 假设 serverUrl 已定义
const serverUrl = window.SMARTINPUT_SERVER_URL || 'https://localhost:3001';

// 初始化函数
function initializeSmartInput() {
  console.log('🚀 SmartInput 内容脚本初始化开始...');
  
  // 设置消息监听器
  setupMessageListener();
  
  // 初始化Socket连接（可选）
  // initializeSocket();
  
  console.log('✅ SmartInput 内容脚本初始化完成');
}

// 设置消息监听器
function setupMessageListener() {
  console.log('📨 设置消息监听器...');
  
  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('📨 收到消息:', message.type, message);
    
    try {
      switch (message.type) {
        case 'INSERT_TEXT':
          console.log('📝 处理INSERT_TEXT消息:', message.text);
          insertTextToActiveInput(message.text, message.confidence);
          sendResponse({ success: true });
          break;
          
        case 'VOICE_TEXT':
          console.log('🎤 处理VOICE_TEXT消息:', message.text);
          handleVoiceText(message.text, message.confidence);
          sendResponse({ success: true });
          break;
          
        case 'TOGGLE_AUTO_INSERT':
          console.log('🔄 切换自动插入状态:', message.enabled);
          isAutoInsertEnabled = message.enabled;
          sendResponse({ success: true, autoInsert: isAutoInsertEnabled });
          break;
          
        case 'GET_STATUS':
          console.log('📊 获取状态请求');
          sendResponse({ 
            success: true, 
            autoInsert: isAutoInsertEnabled,
            currentInput: currentInputElement ? currentInputElement.tagName + (currentInputElement.id ? '#' + currentInputElement.id : '') : null
          });
          break;
          
        case 'TEST_MESSAGE':
          console.log('🧪 收到测试消息:', message.data);
          sendResponse({ success: true, received: true, timestamp: Date.now() });
          break;
          
        default:
          console.log('❓ 未知消息类型:', message.type);
          sendResponse({ error: 'Unknown message type' });
      }
    } catch (error) {
      console.error('❌ 处理消息时出错:', error);
      sendResponse({ error: error.message });
    }
    
    return true; // 保持消息通道开放
  });
  
  console.log('✅ 消息监听器设置完成');
}

// 初始化 socket 连接
async function initializeSocket() {
  try {
    console.log('开始初始化 Socket.IO 连接...');
    const io = await loadSocketIO();
    
    if (!io || typeof io !== 'function') {
      throw new Error('io 函数不可用');
    }
    
    console.log('创建 Socket.IO 连接:', serverUrl);
    socket = io(serverUrl, {
      reconnection: true,
      reconnectionAttempts: Infinity,
      reconnectionDelay: 2000,
      transports: ['websocket']
    });
    
    setupSocketHandlers();
    console.log('Socket.IO 连接初始化完成');
  } catch (error) {
    console.error('Socket.IO 初始化失败:', error);
    // 显示错误通知
    showNotification('连接失败', '无法连接到服务器，请检查网络连接', 'error');
  }
}

// 设置 socket 事件处理器
function setupSocketHandlers() {
  if (!socket) return;
  
  // 连接成功
  socket.on('connect', () => {
    updateStatus('已连接');
    restorePairingIfNeeded();
  });

  // 断开连接
  socket.on('disconnect', () => {
    updateStatus('未连接，自动重连中...');
  });

  // 正在重连
  socket.on('reconnect_attempt', () => {
    updateStatus('正在尝试重连...');
  });

  // 配对成功/状态变化
  socket.on('pairingStatus', (data) => {
    updatePairingUI(data);
    savePairingInfo(data);
  });
}

// 本地存储配对信息
function savePairingInfo(pairingInfo) {
  localStorage.setItem('smartinput_pairing', JSON.stringify(pairingInfo));
}
function getPairingInfo() {
  const info = localStorage.getItem('smartinput_pairing');
  return info ? JSON.parse(info) : null;
}

// 自动恢复配对
function restorePairingIfNeeded() {
  const pairingInfo = getPairingInfo();
  if (pairingInfo) {
    socket.emit('restorePairing', pairingInfo);
  }
}

// UI刷新（需根据实际DOM结构调整）
function updateStatus(msg) {
  const el = document.getElementById('status');
  if (el) el.innerText = msg;
}
function updatePairingUI(data) {
  const el = document.getElementById('pairedDeviceId');
  if (el) el.innerText = data.pairedDeviceId || '-';
}



// 处理语音文字
function handleVoiceText(text, confidence = 1.0) {
  console.log('收到语音文字:', text, '置信度:', confidence);
  
  if (!isAutoInsertEnabled) {
    showNotification('自动录入已禁用', '请手动点击输入框后重试', 'warning');
    return;
  }
  
  // 尝试找到最佳输入框
  const targetElement = findBestInputElement();
  
  if (targetElement) {
    // 高亮显示目标输入框
    highlightInputElement(targetElement);
    
    // 插入文字
    insertText(targetElement, text);
    
    // 显示成功反馈
    showInsertionFeedback(targetElement, text, confidence);
    
    // 记录最后插入的文字
    lastInsertedText = text;
    
    console.log('文字已插入到:', targetElement);
  } else {
    // 没有找到合适的输入框，显示引导
    showInputGuidance(text);
    console.log('未找到合适的输入框，显示引导');
  }
}

// 增强型插入函数
function insertTextToActiveInput(text) {
  let active = document.activeElement;
  if (
    active &&
    (
      (active.tagName === 'INPUT' && ['text', 'search', 'email', 'url', 'tel', 'number', 'password'].includes(active.type)) ||
      active.tagName === 'TEXTAREA'
    )
  ) {
    active.focus();
    const oldValue = active.value;
    active.value += text;
    // 触发 input 和 change 事件
    active.dispatchEvent(new Event('input', { bubbles: true }));
    active.dispatchEvent(new Event('change', { bubbles: true }));
    console.log('[SmartInput] 已插入语音内容到输入框:', {
      tag: active.tagName,
      type: active.type,
      oldValue,
      newValue: active.value
    });
    return true;
  }
  console.warn('[SmartInput] 未找到可插入的输入框，当前 activeElement:', active);
  return false;
}

// 检查是否为输入元素
function isInputElement(element) {
  if (!element) return false;
  
  const tagName = element.tagName.toLowerCase();
  const type = element.type ? element.type.toLowerCase() : '';
  
  // 检查是否为input元素
  if (tagName === 'input') {
    const validTypes = ['text', 'search', 'url', 'email', 'tel', 'password', ''];
    return validTypes.includes(type);
  }
  
  // 检查是否为textarea
  if (tagName === 'textarea') {
    return true;
  }
  
  // 检查是否为可编辑元素
  if (element.contentEditable === 'true') {
    return true;
  }
  
  // 检查是否有role="textbox"
  if (element.getAttribute('role') === 'textbox') {
    return true;
  }
  
  return false;
}

// 查找最佳的输入元素（增强版）
function findBestInputElement() {
  // 优先级：有焦点的 > 最近点击的 > 可见的 > 第一个
  const inputs = document.querySelectorAll('input[type="text"], input[type="search"], input[type="url"], input[type="email"], input[type="tel"], input:not([type]), textarea, [contenteditable="true"], [role="textbox"]');
  
  let bestInput = null;
  let maxScore = 0;
  
  inputs.forEach(input => {
    let score = 0;
    
    // 可见性检查
    const rect = input.getBoundingClientRect();
    if (rect.width > 0 && rect.height > 0) {
      score += 10;
    } else {
      return; // 不可见的元素跳过
    }
    
    // 是否在视口内
    if (rect.top >= 0 && rect.left >= 0 && 
        rect.bottom <= window.innerHeight && 
        rect.right <= window.innerWidth) {
      score += 5;
    }
    
    // 是否有焦点
    if (input === document.activeElement) {
      score += 50; // 大幅提高焦点元素的权重
    }
    
    // 是否最近被点击过
    if (input.dataset.smartInputLastUsed) {
      const lastUsed = parseInt(input.dataset.smartInputLastUsed);
      const timeDiff = Date.now() - lastUsed;
      if (timeDiff < 30000) { // 30秒内
        score += 20;
      } else if (timeDiff < 300000) { // 5分钟内
        score += 10;
      }
    }
    
    // 检查是否为空或光标位置合适
    if (input.value === '' || input.value === null) {
      score += 5; // 空输入框优先
    }
    
    // 检查是否有占位符文本
    if (input.placeholder && input.placeholder.length > 0) {
      score += 3;
    }
    
    // 检查是否在表单中
    if (input.form) {
      score += 2;
    }
    
    // 检查是否为搜索框
    if (input.type === 'search' || input.placeholder?.includes('搜索')) {
      score += 3;
    }
    
    // 检查是否被禁用
    if (input.disabled || input.readOnly) {
      score -= 100; // 大幅降低禁用元素的权重
    }
    
    if (score > maxScore) {
      maxScore = score;
      bestInput = input;
    }
  });
  
  console.log('找到最佳输入框:', bestInput, '得分:', maxScore);
  return bestInput;
}

// 高亮显示输入框
function highlightInputElement(element) {
  // 移除之前的高亮
  const existingHighlight = document.querySelector('.smartinput-highlight');
  if (existingHighlight) {
    existingHighlight.remove();
  }
  
  // 创建高亮元素
  const highlight = document.createElement('div');
  highlight.className = 'smartinput-highlight';
  
  const rect = element.getBoundingClientRect();
  highlight.style.cssText = `
    position: fixed;
    top: ${rect.top - 2}px;
    left: ${rect.left - 2}px;
    width: ${rect.width + 4}px;
    height: ${rect.height + 4}px;
    border: 3px solid #4CAF50;
    border-radius: 4px;
    background: rgba(76, 175, 80, 0.1);
    z-index: 9999;
    pointer-events: none;
    animation: smartinput-highlight-pulse 1s ease-in-out;
  `;
  
  document.body.appendChild(highlight);
  
  // 2秒后移除高亮
  setTimeout(() => {
    if (highlight.parentNode) {
      highlight.style.animation = 'smartinput-highlight-fade 0.5s ease-out';
      setTimeout(() => {
        if (highlight.parentNode) {
          highlight.parentNode.removeChild(highlight);
        }
      }, 500);
    }
  }, 2000);
}

// 插入文字到指定元素
function insertText(element, text) {
  console.log('开始插入文字到元素:', element, '文字:', text);
  
  // 记录使用时间
  element.dataset.smartInputLastUsed = Date.now().toString();
  
  try {
    if (element.contentEditable === 'true') {
      // 处理可编辑元素
      insertTextToContentEditable(element, text);
    } else {
      // 处理input和textarea
      insertTextToInputElement(element, text);
    }
    
    // 触发输入事件
    element.dispatchEvent(new Event('input', { bubbles: true }));
    element.dispatchEvent(new Event('change', { bubbles: true }));
    
    // 聚焦到元素
    element.focus();
    
    console.log('文字插入成功');
  } catch (error) {
    console.error('文字插入失败:', error);
    showNotification('插入失败', `无法插入文字: ${error.message}`, 'error');
  }
}

// 插入文字到input/textarea元素
function insertTextToInputElement(element, text) {
  console.log('插入文字到input/textarea:', element.tagName, element.type);
  
  const start = element.selectionStart || 0;
  const end = element.selectionEnd || 0;
  const currentValue = element.value || '';
  
  const newValue = currentValue.substring(0, start) + text + currentValue.substring(end);
  element.value = newValue;
  
  // 设置光标位置
  const newCursorPos = start + text.length;
  element.setSelectionRange(newCursorPos, newCursorPos);
  element.focus();
  
  console.log('input/textarea插入完成，新值:', newValue);
}

// 插入文字到可编辑元素
function insertTextToContentEditable(element, text) {
  console.log('插入文字到可编辑元素');
  
  element.focus();
  
  const selection = window.getSelection();
  if (selection.rangeCount > 0) {
    const range = selection.getRangeAt(0);
    range.deleteContents();
    range.insertNode(document.createTextNode(text));
    
    // 移动光标到文字末尾
    range.setStartAfter(range.endContainer);
    range.setEndAfter(range.endContainer);
    selection.removeAllRanges();
    selection.addRange(range);
  } else {
    // 如果没有选择范围，直接插入到元素末尾
    element.appendChild(document.createTextNode(text));
  }
  
  console.log('可编辑元素插入完成');
}

// 显示插入反馈
function showInsertionFeedback(element, text, confidence) {
  const feedback = document.createElement('div');
  feedback.className = 'smartinput-feedback';
  feedback.innerHTML = `
    <div class="smartinput-feedback-content">
      <div class="smartinput-icon">🎤</div>
      <div class="smartinput-text">已插入: ${text}</div>
      <div class="smartinput-confidence">置信度: ${Math.round(confidence * 100)}%</div>
    </div>
  `;
  
  // 定位到输入框附近
  const rect = element.getBoundingClientRect();
  feedback.style.cssText = `
    position: fixed;
    top: ${rect.bottom + 5}px;
    left: ${rect.left}px;
    background: linear-gradient(135deg, #4CAF50, #45a049);
    color: white;
    padding: 12px 16px;
    border-radius: 8px;
    font-size: 13px;
    z-index: 10000;
    box-shadow: 0 4px 12px rgba(0,0,0,0.3);
    animation: smartinput-fade-in 0.3s ease-out;
    min-width: 200px;
  `;
  
  document.body.appendChild(feedback);
  
  // 3秒后移除
  setTimeout(() => {
    if (feedback.parentNode) {
      feedback.style.animation = 'smartinput-fade-out 0.3s ease-out';
      setTimeout(() => {
        if (feedback.parentNode) {
          feedback.parentNode.removeChild(feedback);
        }
      }, 300);
    }
  }, 3000);
}

// 显示输入引导
function showInputGuidance(text) {
  const guidance = document.createElement('div');
  guidance.className = 'smartinput-guidance';
  guidance.innerHTML = `
    <div class="smartinput-guidance-content">
      <div class="smartinput-icon">🎯</div>
      <div class="smartinput-title">SmartInput 语音输入</div>
      <div class="smartinput-message">请点击一个文本输入框，然后语音文字将自动录入</div>
      <div class="smartinput-text">待录入文字: "${text}"</div>
      <button class="smartinput-cancel-btn">取消</button>
    </div>
  `;
  
  guidance.style.cssText = `
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: white;
    color: #333;
    padding: 20px;
    border-radius: 12px;
    font-size: 14px;
    z-index: 10001;
    box-shadow: 0 8px 32px rgba(0,0,0,0.3);
    animation: smartinput-scale-in 0.3s ease-out;
    max-width: 350px;
    text-align: center;
  `;
  
  // 添加取消按钮事件
  const cancelBtn = guidance.querySelector('.smartinput-cancel-btn');
  cancelBtn.addEventListener('click', () => {
    guidance.remove();
  });
  
  document.body.appendChild(guidance);
  
  // 10秒后自动移除
  setTimeout(() => {
    if (guidance.parentNode) {
      guidance.style.animation = 'smartinput-scale-out 0.3s ease-out';
      setTimeout(() => {
        if (guidance.parentNode) {
          guidance.parentNode.removeChild(guidance);
        }
      }, 300);
    }
  }, 10000);
}

// 显示通知
function showNotification(title, message, type = 'info') {
  const notification = document.createElement('div');
  notification.className = `smartinput-notification smartinput-${type}`;
  notification.innerHTML = `
    <div class="smartinput-notification-content">
      <div class="smartinput-notification-title">${title}</div>
      <div class="smartinput-notification-message">${message}</div>
    </div>
  `;
  
  const colors = {
    info: '#2196F3',
    success: '#4CAF50',
    warning: '#FF9800',
    error: '#F44336'
  };
  
  notification.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    background: ${colors[type]};
    color: white;
    padding: 12px 16px;
    border-radius: 6px;
    font-size: 14px;
    z-index: 10000;
    box-shadow: 0 4px 12px rgba(0,0,0,0.3);
    max-width: 300px;
    animation: smartinput-slide-in 0.3s ease-out;
  `;
  
  document.body.appendChild(notification);
  
  // 5秒后移除
  setTimeout(() => {
    if (notification.parentNode) {
      notification.style.animation = 'smartinput-slide-out 0.3s ease-out';
      setTimeout(() => {
        if (notification.parentNode) {
          notification.parentNode.removeChild(notification);
        }
      }, 300);
    }
  }, 5000);
}

// 显示无输入框警告
function showNoInputWarning(text) {
  showNotification('未找到输入框', '请点击一个文本输入框后重试', 'warning');
}

// 监听输入框点击，记录最近使用
document.addEventListener('click', (event) => {
  if (isInputElement(event.target)) {
    event.target.dataset.smartInputLastUsed = Date.now().toString();
    currentInputElement = event.target;
    
    // 如果有待录入的文字，立即录入
    if (lastInsertedText && isAutoInsertEnabled) {
      setTimeout(() => {
        insertText(event.target, lastInsertedText);
        showInsertionFeedback(event.target, lastInsertedText, 1.0);
        lastInsertedText = '';
      }, 100);
    }
  }
});

// 监听输入框焦点
document.addEventListener('focusin', (event) => {
  if (isInputElement(event.target)) {
    currentInputElement = event.target;
    event.target.dataset.smartInputLastUsed = Date.now().toString();
  }
});

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
  @keyframes smartinput-fade-in {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
  }
  
  @keyframes smartinput-fade-out {
    from { opacity: 1; transform: translateY(0); }
    to { opacity: 0; transform: translateY(-10px); }
  }
  
  @keyframes smartinput-slide-in {
    from { opacity: 0; transform: translateX(100%); }
    to { opacity: 1; transform: translateX(0); }
  }
  
  @keyframes smartinput-slide-out {
    from { opacity: 1; transform: translateX(0); }
    to { opacity: 0; transform: translateX(100%); }
  }
  
  @keyframes smartinput-scale-in {
    from { opacity: 0; transform: translate(-50%, -50%) scale(0.8); }
    to { opacity: 1; transform: translate(-50%, -50%) scale(1); }
  }
  
  @keyframes smartinput-scale-out {
    from { opacity: 1; transform: translate(-50%, -50%) scale(1); }
    to { opacity: 0; transform: translate(-50%, -50%) scale(0.8); }
  }
  
  @keyframes smartinput-highlight-pulse {
    0% { box-shadow: 0 0 0 0 rgba(76, 175, 80, 0.7); }
    70% { box-shadow: 0 0 0 10px rgba(76, 175, 80, 0); }
    100% { box-shadow: 0 0 0 0 rgba(76, 175, 80, 0); }
  }
  
  @keyframes smartinput-highlight-fade {
    from { opacity: 1; }
    to { opacity: 0; }
  }
  
  .smartinput-feedback-content {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  .smartinput-icon {
    font-size: 16px;
  }
  
  .smartinput-confidence {
    font-size: 11px;
    opacity: 0.8;
  }
  
  .smartinput-guidance-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
  }
  
  .smartinput-cancel-btn {
    background: #f44336;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
  }
  
  .smartinput-cancel-btn:hover {
    background: #d32f2f;
  }
`;

document.head.appendChild(style);

// 页面加载完成后初始化
function initializeContentScript() {
  console.log('🚀 SmartInput 内容脚本开始初始化...');
  
  // 初始化SmartInput功能
  initializeSmartInput();
  
  // 初始化Socket连接（可选，主要用于配对功能）
  // initializeSocket();
  
  console.log('✅ SmartInput 内容脚本初始化完成');
}

// 根据页面加载状态选择初始化时机
if (document.readyState === 'loading') {
  // 页面还在加载中，等待DOMContentLoaded事件
  document.addEventListener('DOMContentLoaded', () => {
    console.log('📄 DOM加载完成，初始化SmartInput');
    setTimeout(initializeContentScript, 500);
  });
} else {
  // 页面已经加载完成，直接初始化
  console.log('📄 页面已加载完成，立即初始化SmartInput');
  setTimeout(initializeContentScript, 500);
}

console.log('📜 SmartInput 内容脚本已加载 - 增强版');
